import { roughPoints, _offset } from "../algorithm/rough.js"
import { _path } from './path.js'
import { _props } from "./canvas.js";
import { _moveTo, _bezierCurveTo, _loop, _polyline } from './curve.js'
import { _random } from "../math/index.js"
import { controlPoints } from '../algorithm/controlPoints.js'
import { fillGridPoints } from '../algorithm/fill.js'


// // 计算两个点连成的线段上左近的一个随机点
// const getNearRandomPoint = ([x1, y1], [x2, y2]) => {
//     let r = 10
//     let xo, yo, rx, ry
//     // 垂直x轴的线段非凡解决
//     if (x1 === x2) {
//         yo = y2 - y1
//         rx = x1 + _random(-2 * r, 2 * r)// 在横坐标左近找一个随机点
//         ry = y1 + yo * _random(0, r)// 在线段上找一个随机点
//         return [rx, ry]
//     }
//     xo = x2 - x1
//     rx = x1 + xo * _random(0, r)// 找一个随机的横坐标
//     ry = ((rx - x1) * (y2 - y1)) / (x2 - x1) + y1// 通过两点式求出直线方程
//     ry += _random(-2 * r, 2 * r)// 纵坐标加一点随机值
//     return [rx, ry]
// }
const _roughTo = (ctx, [from, to], angle, radio) => {
    from = _offset(from)
    to = _offset(to)
    let [c1, c2] = controlPoints([from, to], _random(10, 20), _random(0.1, 0.2))
    _moveTo(ctx, from)
    _bezierCurveTo(ctx, [c1, c2, to])

}

const _dooubleRoughTo = (ctx, [from, to], angle, radio) => {
    _roughTo(ctx, [from, to], angle, radio)
    _roughTo(ctx, [from, to], angle, radio)
}

export const _rough = (ctx, options) => {
    let { points } = options
    let gridDensity = 10

    ctx.save()
    ctx.beginPath()
    _props(ctx, { lineWidth: 2, strokeDasharray: 0 })
    _loop(ctx, options, _dooubleRoughTo)

    ctx.stroke()
    ctx.restore()

    let ps = fillGridPoints({ points, gridDensity })

    ctx.save()
    ctx.beginPath()
    _props(ctx, { stroke: 'gray', strokeDasharray: 4 })

    _loop(ctx, { points: ps, step: 2 }, _roughTo)
    ctx.stroke()
    ctx.restore()

}

// export const _rough = (ctx, options, props) => {
//     let matrix = rougthPoints(options)
//     ctx.save();
//     ctx.beginPath()
//     _props(ctx, props)
//     _path(ctx, {
//         ...options,
//         points: matrix
//     }, props)
//     ctx.stroke()
//     ctx.restore();
// }